package com.selfdiscipline.ui.screens.home

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.data.local.entity.HabitEntity
import com.selfdiscipline.data.local.entity.TaskEntity
import com.selfdiscipline.domain.repository.HabitRepository
import com.selfdiscipline.domain.repository.TaskRepository
import com.selfdiscipline.domain.repository.TimeRecordRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val taskRepository: TaskRepository,
    private val habitRepository: HabitRepository,
    private val timeRecordRepository: TimeRecordRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(HomeUiState())
    val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()
    
    init {
        loadData()
    }
    
    fun completeTask(task: TaskEntity) {
        viewModelScope.launch {
            val updatedTask = task.copy(
                isCompleted = !task.isCompleted,
                completedAt = if (!task.isCompleted) LocalDateTime.now() else null
            )
            taskRepository.updateTask(updatedTask)
            loadData()
        }
    }
    
    // Helper to convert timestamp to LocalDateTime
    private fun Long?.toLocalDateTime(): LocalDateTime? {
        return this?.let {
            LocalDateTime.ofInstant(Instant.ofEpochMilli(it), ZoneId.systemDefault())
        }
    }
    
    private fun loadData() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            
            combine(
                taskRepository.getActiveTasks(),
                taskRepository.getCompletedTasks(),
                habitRepository.getActiveHabits(),
                timeRecordRepository.getAllTimeRecords()
            ) { activeTasks, completedTasks, activeHabits, timeRecords ->
                HomeUiState(
                    isLoading = false,
                    activeTasks = activeTasks,
                    completedTasks = completedTasks,
                    activeHabits = activeHabits,
                    totalFocusedTimeMinutes = timeRecords.sumOf { it.durationMinutes ?: 0 }
                )
            }.collect { newState ->
                _uiState.value = newState
            }
        }
    }
}

data class HomeUiState(
    val isLoading: Boolean = true,
    val activeTasks: List<TaskEntity> = emptyList(),
    val completedTasks: List<TaskEntity> = emptyList(),
    val activeHabits: List<HabitEntity> = emptyList(),
    val totalFocusedTimeMinutes: Int = 0
) 